// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");

const isDev = process.env.NODE_ENV === "development";

function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 1440,
        height: 900,
        webPreferences: {
            preload: path.join(__dirname, "preload.js"),
        },
    });

    // and load the index.html of the app.
    if (isDev) {
        mainWindow.loadURL("http://localhost:3002");
    } else {
        mainWindow.loadFile(`${__dirname}/index.html`);
    }

    // Open the DevTools.
    // mainWindow.webContents.openDevTools({ mode: "detach" });

    // 新版版不支持在渲染层调用 electron，需要使用事件的方式互相通信实现功能 ===============
    // 打印或导出指定 html 片段
    ipcMain.on("print", (event, { htmlContent }) => {
        const _mainWindow = mainWindow;
        _mainWindow.webContents.getPrintersAsync().then((res) => {
            console.log(res);
        });
        // 打印方向、尺寸等未生效
        _mainWindow.webContents.print(
            {
                silent: false,
                landscape: true,
                margins: { marginType: "none" },
                pageSize: "A3",
                // deviceName: deviceName,
            },
            (success, errorType) => {
                if (!success) console.log(errorType);
            }
        );
    });
    // TODO: 有问题，打出的内容是空白的
    ipcMain.on("printHtml", (event, { htmlContent }) => {
        const _mainWindow = new BrowserWindow({
            width: 800,
            height: 600,
            show: false, // 不显示窗口
            frame: false, // 去除边框
            alwaysOnTop: true, // 保持在其他窗口之上
            transparent: true, // 透明背景，避免影响打印预览
        });
        // 加载指定的 HTML 字符串
        const dataUri = `data:text/html;charset=UTF-8,${encodeURIComponent(htmlContent)}`;
        _mainWindow.loadURL(dataUri);
        _mainWindow.once("ready-to-show", () => {
            const printOptions = {
                silent: false, // 不显示打印对话框
                printBackground: true, // 打印网页背景
                deviceName: "", // 留空以使用默认打印机，或指定打印机名称
                margins: { marginType: "none" },
                landscape: true, // 是否横向打印，根据需要设置
            };

            _mainWindow.webContents.print(printOptions, (success, errorType) => {
                if (!success) {
                    console.error(`Printing failed: ${errorType}`);
                }
                _mainWindow.destroy(); // 打印完成后关闭临时窗口
            });
        });

        // 处理加载失败情况
        _mainWindow.webContents.on("did-fail-load", (event, errorCode, errorDescription, validatedURL) => {
            console.error(`Failed to load content for printing: ${errorCode} - ${errorDescription}`);
            _mainWindow.destroy();
        });
        // _mainWindow.webContents.executeJavaScript(`
        // document.open();
        // document.write(\`${htmlContent || ""}\`);
        // document.close();
        // `);
        return;
    });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    createWindow();

    app.on("activate", function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
    if (process.platform !== "darwin") app.quit();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
